package org.wlgzs.office_exam_student.dao;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.dbutils.BeanProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author song(mejeesong@qq.com) 2018年1月28日
 *
 */
class HumpBeanProcessor {
@SuppressWarnings("rawtypes")
private static Map<Class,Map<String,String>> columnToPropertyCache = new ConcurrentHashMap<>();

	private static Logger logger = LoggerFactory.getLogger(HumpBeanProcessor.class);
	
	@SuppressWarnings("rawtypes")
	public static BeanProcessor generate(Class c) {
		Map<String, String> colomnToProperty = columnToPropertyCache.get(c);
		if(colomnToProperty == null) {
			colomnToProperty = generateColumnToProperty(c);
		}
		return new BeanProcessor(colomnToProperty);
	}
	
	@SuppressWarnings("rawtypes")
	protected static  Map<String,String> generateColumnToProperty(Class c){
		Map<String,String> columnToProperty = new HashMap<>();
		Field[] fields = c.getDeclaredFields();
		StringBuilder columnName = new StringBuilder();
		for(Field f:fields) {
			String fName = f.getName();
			char[] fNameChars = fName.toCharArray();
			for(char cr:fNameChars) {
				//先判断小于等于‘Z’减少判断次数
				if( cr <= 'Z' && cr >= 'A') {
					columnName.append('_');
					columnName.append((char)(cr+32));
					continue;
				}
				columnName.append(cr);
			}
			logger.debug("c:{},f:{}",columnName.toString(),fName);
			columnToProperty.put(columnName.toString(), fName);
			columnName.setLength(0);
		}
		columnToPropertyCache.put(c, columnToProperty);
		return columnToProperty;
	}
	
}
